package com.eostoken.eos_wallet.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.MapUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.eostoken.eos_wallet.R;
import com.eostoken.eos_wallet.base.BaseActivity;
import com.eostoken.eos_wallet.bean.BindMidBean;
import com.eostoken.eos_wallet.bean.MsgCodeBean;
import com.eostoken.eos_wallet.db.MgpWallet;
import com.eostoken.eos_wallet.helper.DialogConfirmListener;
import com.eostoken.eos_wallet.helper.DialogHelper;
import com.eostoken.eos_wallet.mvp.mode.AppsModel;
import com.eostoken.eos_wallet.mvp.presenter.AppsPresenterImpl;
import com.eostoken.eos_wallet.mvp.view.AppsView;
import com.eostoken.eos_wallet.utils.Constants;
import com.eostoken.eos_wallet.utils.RSAUtils;
import com.eostoken.eos_wallet.utils.WalletUtils;
import com.qmuiteam.qmui.layout.QMUIRelativeLayout;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.eostoken.eos_wallet.utils.Constants.BIND_MID;
import static com.eostoken.eos_wallet.utils.Constants.IS_FIND_MID;

public class ActivateMidActivity extends BaseActivity<AppsModel, AppsView, AppsPresenterImpl> implements AppsView {

    @BindView(R.id.topBar)
    QMUITopBar topBar;
    @BindView(R.id.walletIconTv)
    QMUIRadiusImageView walletIconTv;
    @BindView(R.id.walletNameTv)
    AppCompatTextView walletNameTv;
    @BindView(R.id.walletAccountTv)
    AppCompatTextView walletAccountTv;
    @BindView(R.id.walletInfoLayout)
    QMUIRelativeLayout walletInfoLayout;
    @BindView(R.id.inviterEt)
    AppCompatEditText inviterEt;
    @BindView(R.id.nextstepBtn)
    QMUIRoundButton nextstepBtn;

    private int mRadius;
    private String accountName;
    private MgpWallet wallet;
    private String parentMid;
    private QMUIDialog qmuiDialog;
    private BindMidBean bindMidBean;


    @Override
    public int getContentView() {
        return R.layout.activity_activate_mid;
    }

    @Override
    protected void initData() {
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.app_color_blue));
        BarUtils.setStatusBarLightMode(this, false);
        wallet = WalletUtils.getCurrentWallet(this);
        mRadius = QMUIDisplayHelper.dp2px(this, 8);
        accountName = wallet.getCurrentAccountName();
        isFindMIDBinding();
    }

    @Override
    public void initView() {
        topBar.setTitle(getString(R.string.str_mid_activate));
        topBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        walletInfoLayout.setRadius(mRadius);
        walletNameTv.setText(wallet.getWalletName());
        walletAccountTv.setText(accountName);

    }

    @Override
    public boolean isShowState() {
        return true;
    }

    @OnClick({R.id.qrCodeIv, R.id.nextstepBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.qrCodeIv:
                startQrCode();
                break;
            case R.id.nextstepBtn:
                if (qmuiDialog == null) {
                    qmuiDialog = DialogHelper.showEditTextDialog(ActivateMidActivity.this, getString(R.string.str_password_authentification),
                            getString(R.string.str_enter_password), getString(android.R.string.ok), getString(android.R.string.cancel), listener, true);
                }
                qmuiDialog.show();
                break;
        }
    }

    DialogConfirmListener listener = new DialogConfirmListener() {
        @Override
        public void onClick(QMUIDialog dialog, View view, int index) {
            dialog.dismiss();
            EditText editText = (EditText) view;
            String contrastPassword = editText.getText().toString().trim();
            if (ObjectUtils.equals(contrastPassword, wallet.getWalletPassword())) {
                try {
                    parentMid = inviterEt.getText().toString().trim();
                    if (ObjectUtils.isEmpty(parentMid)) {
                        ToastUtils.showShort(StringUtils.getString(R.string.str_please_enter_inviter));
                    } else {
                        Map params = MapUtils.newHashMap();
                        params.put("mgpName", accountName);
                        params.put("parentMid", parentMid);
                        String jsonData2 = GsonUtils.toJson(params);
                        String content = RSAUtils.encrypt(jsonData2);
                        presenter.requestPortData(content, BIND_MID);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                ToastUtils.showShort(StringUtils.getString(R.string.str_wrong_password));
            }
            editText.setText("");
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constants.REQUEST_SCAN_CODE:
                if (!ObjectUtils.isEmpty(data)) {
                    Bundle bundle = data.getExtras();
                    String scanResult = bundle.getString(Constants.INTENT_EXTRA_KEY_QR_SCAN);
                    if (!ObjectUtils.isEmpty(scanResult)) {
                        parentMid = scanResult;
                        inviterEt.setText(parentMid);
                    }
                }
                break;
            default:
        }
    }

    @Override
    public void updateView(Object data, int responseSuccessCode) {
        switch (responseSuccessCode) {
            case BIND_MID:
                if (data != null) {
                    bindMidBean = GsonUtils.fromJson(data.toString(), BindMidBean.class);
                    if (bindMidBean.getCode() == 0) {
                        finish();
                    } else {
                        ToastUtils.showShort(bindMidBean.getMsg());
                    }
                }
                break;
            case IS_FIND_MID:
                if (ObjectUtils.isNotEmpty(data)) {
                    MsgCodeBean msgCodeBean = GsonUtils.fromJson(data.toString(), MsgCodeBean.class);
                    if (msgCodeBean != null) {
                        if (msgCodeBean.getCode() == 0) {
                            setNextstepBtnEnabled(true);
                        } else {
                            setNextstepBtnEnabled(false);
                            ToastUtils.showLong(msgCodeBean.getMsg());
                        }
                    }
                }
                break;
        }
    }

    public void setNextstepBtnEnabled(boolean isEnabled) {
        nextstepBtn.setEnabled(isEnabled);//去掉点击时编辑框下面横线:
        nextstepBtn.setBackgroundColor(isEnabled ? ColorUtils.getColor(R.color.app_color_dark_blue) : ColorUtils.getColor(R.color.app_color_common_gray));//
    }

    @Override
    public void onFailure(Object data, int responseFailCode) {

    }

    @Override
    public void updateView(boolean success, Object o1, Object o2) {

    }

    @Override
    public AppsModel createModel() {
        return new AppsModel();
    }

    @Override
    public AppsView createView() {
        return this;
    }

    @Override
    public AppsPresenterImpl createPresenter() {
        return new AppsPresenterImpl(this);
    }

    /**
     * 开始扫码
     */
    public void startQrCode() {
        PermissionUtils.permission(PermissionConstants.CAMERA, PermissionConstants.STORAGE)
                .rationale(new PermissionUtils.OnRationaleListener() {
                    @Override
                    public void rationale(UtilsTransActivity activity, ShouldRequest shouldRequest) {
                        DialogHelper.showRationaleDialog(ActivateMidActivity.this, shouldRequest);
                    }
                })
                .callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(List<String> permissionsGranted) {
                        Intent intent = new Intent(ActivateMidActivity.this, QrcodeScanActivity.class);
                        startActivityForResult(intent, Constants.REQUEST_SCAN_CODE);
                    }

                    @Override
                    public void onDenied(List<String> permissionsDeniedForever, List<String> permissionsDenied) {

                    }
                }).request();
    }

    private void isFindMIDBinding() {
        try {
            Map params = MapUtils.newHashMap();
            params.put("address", accountName);
            params.put("type", "1");
            String jsonData = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData);
            presenter.requestPortData(content, IS_FIND_MID);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
